const fastify = require("fastify")({
  logger: true,
});

fastify.register(require("@fastify/cors"));

const multer = require("fastify-multer");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/images");
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage: storage, dest: "public/images" });
module.exports = { upload };
fastify.register(multer.contentParser);

const path = require("path");
const fastifyStatic = require("@fastify/static");

fastify.register(fastifyStatic, {
  root: path.join(__dirname, "./../public/images/"),
  prefix: "/public/images/", // 设置访问路径前缀
});

fastify.register(require("@fastify/swagger"), {
  routePrefix: "/swagger",
  swagger: {
    info: {
      title: "Petstore API",
      version: "1.0.0",
    },
    tags: [
      // { name: "Pet", description: "宠物" },
      // { name: "Orders", description: "订单" },
      { name: "Common", description: "公共服务" },
    ],
    schemes: ["http"],
    consumes: ["application/json"],
    produces: ["application/json"],
  },
  exposeRoute: true,
});
fastify.register(require("@fastify/swagger-ui"), {
  routePrefix: "/swagger",
  swagger: {
    url: "/swagger/json",
  },
  exposeRoute: true,
});

const petRoutes = require("./routes/pet");
const ordersRoutes = require("./routes/orders");

const commonRoutes = require("./routes/common");

const tags = {};

// const allRoutes = [...petRoutes, ...ordersRoutes, ...commonRoutes];

const allRoutes = [...commonRoutes];

allRoutes.forEach((route) => {
  const tag = route.config && route.config.tag ? route.config.tag : "default";
  if (!tags[tag]) {
    tags[tag] = [];
  }
  tags[tag].push(route);
});

Object.keys(tags).forEach((tag) => {
  fastify.register(
    (instance, opts, done) => {
      tags[tag].forEach((route) => {
        instance.route(route);
      });
      done();
    },
    { prefix: `/api/${tag}` }
  );
});

const mongoose = require("./utils/MongoDB");

const start = async () => {
  try {
    await fastify.listen({
      port: 3000,
      host: "0.0.0.0",
    });
    mongoose;
    fastify.swagger();
    fastify.log.info(`Server is listening on ${fastify.server.address().port}`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};
start();
